package com.hejie.apigateway.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import reactor.core.publisher.Mono;

@Configuration
public class GatewayConfig {

    /**
     * 路由规则配置
     */
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                // 视频服务路由
                .route("video-service", r -> r.path("/api/videos/**")
                        .filters(f -> f
                                .rewritePath("/api/(?<segment>.*)", "/${segment}")
                                .addResponseHeader("X-Response-Time", "${responseTime}")
                        )
                        .uri("lb://video-service"))

                // 评论服务路由
                .route("comment-service", r -> r.path("/api/comments/**")
                        .filters(f -> f
                                .rewritePath("/api/(?<segment>.*)", "/${segment}")
                                .requestRateLimiter(c -> c
                                        .setRateLimiter(redisRateLimiter())
                                        .setKeyResolver(userKeyResolver())
                                )
                        )
                        .uri("lb://comment-service"))

                // 通知服务路由
                .route("notification-service", r -> r.path("/api/notifications/**")
                        .filters(f -> f
                                .rewritePath("/api/(?<segment>.*)", "/${segment}")
                                .addResponseHeader("X-Response-Time", "${responseTime}")
                        )
                        .uri("lb://notification-service"))

                // 用户服务路由
                .route("user-service", r -> r.path("/api/users/**")
                        .filters(f -> f
                                .rewritePath("/api/(?<segment>.*)", "/${segment}")
                        )
                        .uri("lb://user-service"))
                .build();
    }

    /**
     * Redis限流配置
     */
    @Bean
    public RedisRateLimiter redisRateLimiter() {
        // 令牌桶容量和令牌生成速率
        return new RedisRateLimiter(20, 40);
    }

    /**
     * 限流键解析器 - 使用用户ID作为限流键
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.justOrEmpty(exchange.getRequest().getHeaders().getFirst("X-User-ID"))
                .defaultIfEmpty("anonymous");
    }
}